package com.xingli.jingdongshop.util;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;

public class CDKUtil {
    //base采用URL安全的Encode

    //游戏 类型  时间  序列号 随机数 校验码
    // 2     2      4    4      8    4

    /**
     *
     * @param gameId 游戏Id
     * @param cdkType cdk的类型
     * @param todayLastIndex 今天之内上一次生成的位置，没有为100000
     * @param number 生成的数量
     * @return
     */
    public static List<String> generateCDK(String gameId, String cdkType, String today, int todayLastIndex, int number){
        Base64.Encoder encoder = Base64.getUrlEncoder();
        todayLastIndex++;
        List<String> list = new ArrayList<>(number);
        for (int i = todayLastIndex; i < (todayLastIndex+number); i++) {
            StringBuffer str = new StringBuffer();
            str.append(gameId);
            str.append(cdkType);
            str.append(CommonUtil.randomStr(2));
            str.append(today);
            str.append(CommonUtil.randomStr(2));
            str.append(todayLastIndex);
            str.append(CommonUtil.randomStr(4));
            str.append(encryptStr(str.toString(),"xingli"));
            list.add(encoder.encodeToString(str.toString().getBytes()));
        }
        return list;
    }

    public static String encryptStr(String cdkStr,String encryptStr){
        return CommonUtil.encoderByMd5(cdkStr+encryptStr).substring(10,14);
    }

    public static void main(String[] args) throws InterruptedException {
        String today = LocalDateTime.now().format(DateTimeFormatter.ofPattern("MMdd"));
        int todayLastIndex = getTodayIndex(today);
        generateCDK("BY","HB",today,todayLastIndex,1000);

    }

    public static int getTodayIndex(String today){
        return 1000;
    }
}
